import { useState, useEffect } from 'react';
import { AlmanacData } from '../types/almanac';
import { fetchAlmanacData, fetchYunShiData } from '../services/almanacService';

export function useAlmanacData(date: Date) {
  const [almanacData, setAlmanacData] = useState<AlmanacData | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<Error | null>(null);

  useEffect(() => {
    let mounted = true;

    async function loadAlmanacData() {
      setIsLoading(true);
      setError(null);
      
      try {
        const response = await fetchAlmanacData(date);
        if (mounted && response.code === 1) {
          setAlmanacData(response.data);
        }
      } catch (err) {
        if (mounted) {
          setError(err instanceof Error ? err : new Error('Failed to fetch almanac data'));
        }
      } finally {
        if (mounted) {
          setIsLoading(false);
        }
      }
    }

    loadAlmanacData();

    return () => {
      mounted = false;
    };
  }, [date]);

  return { almanacData, isLoading, error };
}